package com.adams.dcxt.core;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 存取选择菜单但没有下单数据
 * 
 * @author 904912
 * 
 */
public class TableMaps {

	private static Map<String, Set<DishesTemp>> tableMaps = new HashMap<String, Set<DishesTemp>>();

	private static TableMaps instance = null;

	private TableMaps() {
	}

	public static synchronized TableMaps getInstance() {
		if (instance == null) {
			instance = new TableMaps();
		}
		return instance;
	}

	public static void clear(String key) {
		tableMaps.remove(key);
	}

	public static void clearItem(String tableId, String ids) {
		Set set = tableMaps.get(tableId);
		Object obj = null;
		String[] idarr = ids.split(",");
		for (int i = 0; i<idarr.length; i++) {
			Iterator it = set.iterator();
			while (it.hasNext()) {
				DishesTemp tmp = (DishesTemp) it.next();
				if (tmp.getDishesId().longValue() == Long.parseLong(idarr[i])) {
					obj = tmp;
					break;
				}
			}
			if (obj != null) {
				set.remove(obj);
			}
		}
	}

	public static synchronized void setTemp(String tableId, DishesTemp tmp) {
		Set<DishesTemp> tmpSet = tableMaps.get(tableId);
		if (tmpSet == null) {
			tmpSet = new HashSet<DishesTemp>();
			tmpSet.add(tmp);
			tableMaps.put(tableId, tmpSet);
		} else {
			String counts = tmp.getCount();
			boolean iseuqals = true;
			for (DishesTemp vo : tmpSet) {
				if (vo.getDishesId().intValue() == tmp.getDishesId().intValue()) {
					// 已经选择过这个菜，把份数加上
					int old = Integer.parseInt(vo.getCount());
					int newCount = old + Integer.parseInt(counts);
					counts = String.valueOf(newCount);
					vo.setCount(counts);
					iseuqals = false;
					break;
				}
			}
			if (iseuqals) {
				tmpSet.add(tmp);
			}

		}
	}

	public static Map<String, Set<DishesTemp>> getTemps() {
		return tableMaps;
	}

	public static Set<DishesTemp> getTempsByTableId(String key) {
		Set<DishesTemp> set = tableMaps.get(key);
		return set;
	}
}
